package com.mine.java.future;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author weixiao
 * @date 2025/3/26 16:29
 */
public class AllOfTest {

    public static CompletableFuture<Long> countWord(String fileName, String targetWord) {
        return CompletableFuture.supplyAsync(() -> {
            long count = 0;
            try {
                PrintUtils.print("执行统计单个文件中" + targetWord + "个数的任务");
                BufferedReader bf = new BufferedReader(new FileReader(fileName));
                String line;
                while ((line = bf.readLine()) != null) {
                    if (line.contains(targetWord)) {
                        count++;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return count;
        });
    }

    public static void main(String[] args) {
        // 需求：统计多个文件中Idea出现的次数
        PrintUtils.print("任务开始");
        // 1.创建多个CompletableFuture分别读取不同文件中Idea出现的次数
        List<String> fileList = Arrays.asList("1.txt", "2.txt", "3.txt");
        List<CompletableFuture<Long>> futureList = fileList.stream().map(f -> AllOfTest.countWord(f, "Idea")).collect(Collectors.toList());
        // 2.汇总任务
        CompletableFuture<Void> allOfFutures = CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]));
        // 3.统计总的个数
        CompletableFuture<Long> countFuture = allOfFutures.thenApply(v -> {
            PrintUtils.print("汇总所有Future的执行结果");
            long count = 0;
            for (CompletableFuture<Long> f : futureList) {
                count += f.join();
            }
            return count;
        });
        PrintUtils.print(countFuture.join() + "");
        PrintUtils.print("任务结束");
    }
}
